iT邦幫忙

2026 iThome 鐵人賽

DAY 1
0
自我挑戰組

學習python連續30天系列 第 1

Python 30 天學習挑戰 Day 1|Global Scope(全域變數)與 Local Scope(區域變數)

  • 分享至 

  • xImage
  •  

今天學到的是 Python 裡很重要的一個觀念:Global Scope(全域範圍)與 Local Scope(區域範圍)。
一開始我其實很容易搞混,明明變數名稱都一樣,為什麼函式裡面的值和函式外面的值會不一樣?
例如:
''''
enemies = 1

def increase_enemies():
enemies = 2
print(f"函式裡的 enemies:{enemies}")

increase_enemies()

print(f"函式外的 enemies:{enemies}")
''''

執行結果會是:
函式裡的 enemies:2
函式外的 enemies:1

解釋
enemies = 2 是一個 Local Variable(區域變數),它只存在於 increase_enemies() 這個函式裡面

enemies = 1 則是 Global Variable(全域變數)

函式外建立的變數 → Global Scope

函式內建立的變數 → Local Scope

global → 在函式內指定要使用外面的變數


下一篇
用python找質數
系列文
學習python連續30天3
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言